package com.demo.algorithm;

/**
 * Created by hunter
 *
 * @Description 冒泡排序(从首位或者末尾开始相邻的两个值逐一比较交换, 将最大或最小值交换到首位或末尾)
 */
public class BubbleSort {

    /**
     * 排序方法
     * <p>
     * 此处可有优化, 在第一轮内循环时, 若没有产生值交换, 则外面的循环可以跳过, 这种情况可以为已经排序好的数组...
     *
     * @param numbers
     */
    public static void sort(Integer[] numbers) {
        if (numbers == null || numbers.length == 0) {
            return;
        }

        int length = numbers.length;
        for (int i = 0; i < length - 1; i++) {
            for (int j = 0; j < length - i - 1; j++) {
                if (numbers[j] > numbers[j + 1]) {
                    int t = numbers[j];
                    numbers[j] = numbers[j + 1];
                    numbers[j + 1] = t;
                }
            }
        }
    }

    public static void main(String[] args) {
        Integer[] numbers = {5, 3, 2, 8, 1, 8, 9};
        sort(numbers);
        print(numbers);
    }

    private static void print(Integer[] numbers) {
        for (Integer i : numbers) {
            System.out.println(i);
        }
    }
}
